package com.sry.blog.interceptor;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.sry.blog.common.api.CommonResult;
import com.sry.blog.enums.CheckToken;
import com.sry.blog.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@Component
public class UserLoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
//        log.info("token:{}===========",token);
        if (token == null){
            doResponse(response,CommonResult.failed("token为空，请重新登录"));
            return false;
        }else {
            final CheckToken checkToken = TokenUtil.verifyToken(token);
            if (!checkToken.isFlag()){
                doResponse(response,CommonResult.failed(checkToken));
            }
            return checkToken.isFlag();
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }


    private void doResponse(HttpServletResponse response, CommonResult commonResult) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String s =new ObjectMapper().writeValueAsString(commonResult);
        out.println(s);
        out.flush();
        out.close();
    }
}
